package com.txc.cloud.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txc.cloud.admin.entity.RoleEntity;
import com.txc.cloud.admin.entity.RolePermissionEntity;
import com.txc.cloud.admin.mapper.RoleMapper;
import com.txc.cloud.admin.mapper.RolePermissionMapper;
import com.txc.cloud.admin.model.dto.RoleDto;
import com.txc.cloud.admin.model.vo.RoleVo;
import com.txc.cloud.admin.service.IRoleDeptService;
import com.txc.cloud.admin.service.IRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static com.txc.common.config.mybatisplus.constant.DataScopeConstants.DATA_SCOPE_CUSTOM;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author TXC
 * @since 2023-08-02
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, RoleEntity> implements IRoleService {

    @Resource
    private IRoleDeptService roleDeptService;
    @Resource
    private RolePermissionMapper rolePermissionMapper;
    @Override
    public RoleEntity createRole(RoleDto role) {
        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(role, roleEntity);
        boolean res = roleEntity.insert();
        if (res && DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
            roleDeptService.flush(roleEntity.getId(), role.getDeptIds());
        }
        return roleEntity;
    }

    @Override
    public void updateRole(RoleDto role) {
        RoleEntity roleEntity = new RoleEntity();
        BeanUtils.copyProperties(role, roleEntity);
        boolean res = roleEntity.updateById();
        if (res && DATA_SCOPE_CUSTOM.equals(role.getDataScope())) {
            roleDeptService.flush(roleEntity.getId(), role.getDeptIds());
        }
    }

    @Override
    public boolean empower(Long id, List<String> permissionCodes) {
        AtomicInteger count = new AtomicInteger();
        permissionCodes.forEach(permissionCode -> {
            RolePermissionEntity rolePermissionEntity = new RolePermissionEntity();
            rolePermissionEntity.setRoleId(id);
            rolePermissionEntity.setPermissionCode(permissionCode);
            rolePermissionMapper.insert(rolePermissionEntity);
            count.getAndIncrement();
        });
        return count.get() > 0;
    }

    @Override
    public List<RoleVo> getRoleList() {
        List<RoleVo> res = baseMapper.getRoleList();
        res.forEach(role -> {
            role.setDeptIds(roleDeptService.getDeptIds(role.getId()));
        });
        return res;
    }

}
